/*
 * Clipboard tool
 *
 * License: LGPL v3
 */
package org.passwordstore.util;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import org.passwordstore.Resource;

/**
 *
 * @author thotheolh
 */
public class DataClipboard implements ClipboardOwner {

    private Resource res;
    private Clipboard clipboard;

    public DataClipboard(Resource res) {
        this.res = res;
        init();
    }

    public void init() { //init()
        Toolkit tk = Toolkit.getDefaultToolkit();
        clipboard = tk.getSystemClipboard();
    }

    public void copy(String text) { //Copy clipboard
        StringSelection content = new StringSelection(text);
        clipboard.setContents(content, this);
    }

    public String paste() { //Paste clipboard
        Transferable clipboardContent = clipboard.getContents(this);
        if ((clipboardContent != null) &&
                (clipboardContent.isDataFlavorSupported(DataFlavor.stringFlavor))) {
            try {
                String tempString;
                tempString = (String) clipboardContent.getTransferData(DataFlavor.stringFlavor);
                return tempString;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        } else {
            return null;
        }
    }

    public void clear() { //Clear clipboard
        clipboard.setContents(new Transferable() {

            @Override
            public DataFlavor[] getTransferDataFlavors() {
                return new DataFlavor[0];
            }

            @Override
            public boolean isDataFlavorSupported(DataFlavor flavor) {
                return false;
            }

            @Override
            public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
                //throw new UnsupportedOperationException("Not supported yet.");
                return null;
            }
        }, null);
    }

    @Override
    public void lostOwnership(Clipboard clipboard, Transferable contents){  //Check if ownership of clipboard is lost
        //System.out.println("Lost ownership of clipboard.");//Dianostics
    }
}
